package com.yupi.usercenter.job;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.yupi.usercenter.model.domain.User;
import com.yupi.usercenter.service.UserService;
import lombok.extern.slf4j.Slf4j;
import org.redisson.api.RLock;
import org.redisson.api.RedissonClient;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.ValueOperations;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.util.Arrays;
import java.util.List;
import java.util.concurrent.TimeUnit;

@Slf4j
@Component // 加载成bean
public class PreCacheJob {
    @Resource
    private UserService userService;

    @Resource
    private RedisTemplate<String,Object> redisTemplate;

    @Resource
    private RedissonClient redissonClient;

    //重点用户  
    private List<Long> mainUserList = Arrays.asList(1l);

    //每天执行，预热推荐用户 秒-分-时-日-月-年
    @Scheduled(cron = "00 00 00 * * *")
    public void doCacheRecommendUser(){
        RLock lock = redissonClient.getLock("yunpao:precachejob:docache:%");
        try {
            if (lock.tryLock(0,-1,TimeUnit.MILLISECONDS)) {
                for (Long userId: mainUserList){
                    QueryWrapper<User> queryWrapper = new QueryWrapper<>();
                    Page<User> userPage = userService.page(new Page<>(1, 20), queryWrapper);
                    String redisKey = String.format("yupao:user:recommend:%s", userId);
                    ValueOperations<String,Object> valueOperations = redisTemplate.opsForValue();
                    //写缓存
                    try {
                        valueOperations.set(redisKey,userPage,30000, TimeUnit.MILLISECONDS);
                        log.info("redis预热设置成功");
                    }catch (Exception e){
                        log.error("redis预热设置失败",e);
                    }
                }

            }
        } catch (InterruptedException e) {
            throw new RuntimeException(e);
        }
        finally {
            //放在finally中，避免出现异常无法释放锁
            if (lock.isHeldByCurrentThread()) {
                lock.unlock(); // 释放当前线程的锁
            }
        }

    }
}